import { apiURL } from "../configs/env.config"
import {
	Encrypt, IVStr
} from "./aesUtils"
import {
	RandomCode
} from "./lib"
import {
	RsaEncrypto
} from "./rsaUtils"


let isGetChannelCode = false;
let getChannelCodePromise;

export const getChannelCodeAsync = () => {
	const channelCodeTemp = uni.getStorageSync("channelCode")
	if (channelCodeTemp) return channelCodeTemp;
	return 'default';
}

export const getChannelCode = async () => {
	const channelCodeTemp = uni.getStorageSync("channelCode")
	if (channelCodeTemp && isGetChannelCode) return channelCodeTemp;
	
	const fun = () => {
		const baseHeader = { channelCode: 'default' }
		const accountInfo = uni.getAccountInfoSync();
		const {scene, query} = wx.getLaunchOptionsSync()
		const jsons = JSON.stringify({wxAppid: accountInfo.miniProgram.appId, scene, query})
		// console.log("请求参数", jsons)
		const randonCode = RandomCode.code(32)
		const tranDataBase = Encrypt(jsons, randonCode);
		const ciphertext = RsaEncrypto.encodeString(JSON.stringify({
			iv: IVStr,
			key: randonCode
		}));
		const dataTemp = {
			appId: 'testApp',
			version: '1.0.1',
			tranData: tranDataBase,
			ciphertext,
		}
		
		return new Promise((resolve, reject) => {
			uni.request({
				url: `${apiURL}/sys/getChannelCode`,
				method: 'POST',
				data: dataTemp,
				header: baseHeader,
				success: (res) => {
					const data = res.data
					if (data?.rspCode != '0001'){
						const msg = data?.rspMsg || data?.respMsg;
						uni.showToast({
							title: msg || "获取渠道号失败",
							icon: 'error'
						})
						return reject(new Error(msg))
					}
					const channelCode = data.data.channelCode;
					if (!channelCode) return reject(new Error("渠道号返回错误"))
					uni.setStorageSync("channelCode", channelCode)
					isGetChannelCode = true;
					resolve(channelCode)
				},
				fail: (err) => {
					reject(err)
				}
			})
		})
		
	}
	getChannelCodePromise || (getChannelCodePromise = fun());
	if (!channelCodeTemp) return await getChannelCodePromise;
	return channelCodeTemp
}

export const request = async (url, data) => {
	const channelCode = await getChannelCode()
	const baseHeader = { channelCode }

	const jsons = JSON.stringify(data || {})
	// console.log("请求参数", jsons)
	const randonCode = RandomCode.code(32)
	const tranDataBase = Encrypt(jsons, randonCode);
	const ciphertext = RsaEncrypto.encodeString(JSON.stringify({
		iv: IVStr,
		key: randonCode
	}));
	const dataTemp = {
		appId: 'testApp',
		version: '1.0.1',
		tranData: tranDataBase,
		ciphertext,
	}
	// return Promise.resolve('');
	return await new Promise((resolve, reject) => {
		uni.request({
			url: `${apiURL}/${url}`,
			method: 'POST',
			data: dataTemp,
			header: baseHeader,
			success: (res) => {
				const data = res.data
				if (data?.rspCode != '0001'){
					const msg = data?.rspMsg || data?.respMsg;
					return reject(new Error(msg))
				}
				resolve(data)
			},
			fail: (err) => {
				reject(err)
			}
		})
		
	})
}